<template>
  <div
    ref="barChart"
    :style="{ width: 'inherit', height: `${height}px` }"
  ></div>
</template>
<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from "vue";
import * as echarts from "echarts/core";
import { BarChart } from "echarts/charts";
import { SVGRenderer } from "echarts/renderers";
import { TooltipComponent, GridComponent } from "echarts/components";
import debounce from "lodash/debounce";
echarts.use([BarChart, SVGRenderer, TooltipComponent, GridComponent]);
import type { Point } from "../../types/charts";
const barChart = ref<HTMLElement | null>(null);

const { height = 350, data = [] } = defineProps<{
  height?: number;
  data: Array<Point>;
}>();
let chart: echarts.ECharts | null = null;
const renderChart = () => {
  if (barChart.value) {
    chart = echarts.init(barChart.value, void 0, { renderer: "svg" });
    const option = {
      tooltip: {},
      xAxis: {
        data: data.map((item) => item.x),
      },
      yAxis: {},
      series: [
        {
          name: "访问量",
          type: "bar",
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#ff3333" },
              { offset: 0.5, color: "#ff6633" },
              { offset: 1, color: "#ff9933" },
            ]),
            borderRadius: [8, 8, 0, 0],
          },
          data: data.map((item) => item.y),
        },
      ],
    };
    chart.setOption(option);
  }
};
const resizeRender = debounce(() => {
  chart && chart.resize();
}, 240);
onMounted(() => {
  renderChart();
  window.addEventListener("resize", resizeRender);
});
onUnmounted(() => {
  window.addEventListener("resize", resizeRender);
});
</script>
